<template>
  <a-modal
    :title="`${model&&model.id>0?'编辑':'新增'}用户`"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled/>
        </a-form-item>
        <a-form-item label="登录名称" has-feedback>
          <a-input :disabled="model && model.id > 0" v-decorator="['loginName',{rules: [{ required: true, message: '请输入登录名称' },{ validator: loginNameValidator}], trigger: 'blur' }]"/>
        </a-form-item>
        <a-form-item label="用户名称">
          <a-input v-decorator="['name']"/>
        </a-form-item>
        <a-form-item label="密码">
          <a-input v-decorator="['password']"/>
        </a-form-item>
        <a-form-item label="联系电话">
          <a-input v-decorator="['telephone']"/>
        </a-form-item>
        <a-form-item label="角色">
          <a-input v-decorator="['roleId']"/>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { exist } from '@/api/manage'
// 表单字段
const fields = ['id', 'loginName', 'name', 'password', 'telephone', 'roleId']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      formLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 13 }
        }
      },
      form: this.$form.createForm(this)
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    loginNameValidator(rule, value, callback) {
      if (this.model.id > 0) {
        callback()
      }
      exist('t_user', 'loginName', value).then(response => {
        response.success ? callback() : callback(response.message)
      }).catch(error => {
        callback(error && error.message || '远程校验异常')
      })
    }

  }
}
</script>
